import React, { FC, useState } from 'react'
import { Form, Button, Divider, Select, message, Input } from 'antd'
import TopHeader, { ListTitle } from '~/components/top-header'
import SuccessModal from '~/components/submit-successfully'
import ProductionVoucher from '~/components/production-voucher'
import UploadCom from '~/components/my-upload'
import { useNavigate, useLocation } from 'react-router-dom'
import { queryCastItems, handleTake, queryWaitCastItems } from '~/api/handle-property-api'
import { getUserInfo } from '~/mock/user/userinfo'
import useGetMembers from '~/hooks/useGetMembers'
import { HandleItemsMap, TaskItemMap } from '~/constants'

import { FooterAction } from './styled'
import WaitingList from './container/waiting-list'
import MovedList from './container/moved-list'
import PropertySelect from './components/property-involved-select'

const { Option } = Select
const { TextArea } = Input
const docs = new Map()
const dealPics = new Map()
const userInfoData = JSON.parse(localStorage.getItem('u')!)

const PropertyInvolved: FC = () => {
  const [form] = Form.useForm()
  const navigate = useNavigate()
  const { state } = useLocation()
  const [successVisible, setSuccessVisible] = useState(false)
  const [certificateVisible, setCertificateVisible] = useState(false)
  const [selectVisible, setSelectVisible] = useState(false)
  const [isShowRemark, setIsShowRemark] = useState(false)
  const [castItems, setCastItems] = useState([])
  const [selectedItems, setSelectedItems] = useState<any>([])
  const { validateFields } = form
  const {
    batchNo,
    caseNo,
    caseName,
    caseDepartmentName,
    caseCompanyName,
    caseState,
    createCompanyName,
    createDepartmentName,
    dealUserName,
    dealReason,
    whereabouts,
    whereaboutsRemark
  }: any = state
  const takeMembers = useGetMembers(userInfoData.departmentCode)
  const isWait = caseState === 1

  const handleGetCastItems = async (value?: any) => {
    const userInfo = getUserInfo()
    if (isWait) {
      const { data } = await queryWaitCastItems({
        ...userInfo,
        ...value,
        caseNo
      })
      setCastItems(data)
    } else {
      const { data } = await queryCastItems({
        ...value,
        batchNo
      })
      setCastItems(data)
    }
  }

  const onClickBorrowCertficate = async (preview?: boolean) => {
    const userInfo = getUserInfo()
    if (!selectedItems.length) return message.error('请至少选择一个物品')
    const { dealReason, dealUserNo, whereabouts, whereaboutsRemark } = await validateFields()
    const { data } = await handleTake({
      ...userInfo,
      items: selectedItems.map((item: any) => {
        return {
          number: item.itemStock.dealNumber || item.itemStock.currentNumber,
          serialNo: item.itemStock.serialNo,
          unitName: item.itemStock.unitName
        }
      }),
      dealCompanyCode: userInfoData.companyCode,
      dealCompanyName: userInfoData.companyName,
      dealDepartmentCode: userInfoData.departmentCode,
      dealDepartmentName: userInfoData.departmentName,
      caseName,
      caseNo,
      paperDir: 0,
      preview: !!preview,
      dealUserName: takeMembers.find((item: any) => item.userNo === dealUserNo).userName,
      dealUserNo,
      docs: [...docs.values()],
      dealPics: [...dealPics.values()],
      dealReason,
      whereabouts,
      whereaboutsRemark
    })
    window.open(data.url)
    if (preview) return
    setSuccessVisible(true)
  }

  const headData = [
    {
      childen: [
        {
          label: '案件编号:',
          value: caseNo
        },
        { label: '案件名称:', value: caseName }
      ]
    },
    {
      childen: [
        { label: '办案单位:', value: caseCompanyName || createCompanyName },
        { label: '办案部门:', value: caseDepartmentName || createDepartmentName }
      ]
    }
  ]

  return (
    <div>
      <TopHeader headData={headData} />
      <ListTitle />
      <Divider />
      <main style={{ marginTop: 21 }}>
        {isWait ? (
          <WaitingList
            selectedItems={selectedItems}
            handleGetCastItems={handleGetCastItems}
            setSelectVisible={setSelectVisible}
            setSelectedItems={setSelectedItems}
          />
        ) : (
          <MovedList handleGetCastItems={handleGetCastItems} castItems={castItems} />
        )}

        <h3>处理信息</h3>
        <Divider />
        <Form validateTrigger="onBlur" form={form}>
          <Form.Item rules={[{ required: isWait, message: '请选择处理人员' }]} name="dealUserNo" label="处理人员">
            {isWait ? (
              <Select showSearch
                      optionFilterProp="children"
                      filterOption={(input, option) => option!.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                      placeholder="请选择处理人员" style={{ width: 200 }}>
                {takeMembers.map((item: any, index: number) => (
                  <Option value={item.userNo} key={index}>
                    {item.userName}
                  </Option>
                ))}
              </Select>
            ) : (
              <span>{dealUserName}</span>
            )}
          </Form.Item>
          <Form.Item rules={[{ required: isWait, message: '请选择处理事由' }]} name="dealReason" label="处理事由">
            {isWait ? (
              <Select placeholder="请选择处理事由" style={{ width: 200 }}>
                {[...TaskItemMap].map(([key, value], index) => (
                  <Option key={index} value={key}>
                    {value}
                  </Option>
                ))}
              </Select>
            ) : (
              <span>{TaskItemMap.get(dealReason)}</span>
            )}
          </Form.Item>
          <Form.Item rules={[{ required: isWait, message: '请选择物品去向' }]} name="whereabouts" label="物品去向">
            {isWait ? (
              <Select
                onChange={val => {
                  setIsShowRemark(val === 'OTHER')
                }}
                placeholder="请选择物品去向"
                style={{ width: 200 }}
              >
                {[...HandleItemsMap].map(([key, value], index) => (
                  <Option key={index} value={key}>
                    {value}
                  </Option>
                ))}
              </Select>
            ) : (
              <span>{HandleItemsMap.get(whereabouts)}</span>
            )}
          </Form.Item>
          {isShowRemark && (
            <Form.Item name="whereaboutsRemark" label="备注">
              {isWait ? <TextArea style={{ width: 200 }} /> : <span>{whereaboutsRemark}</span>}
            </Form.Item>
          )}
        </Form>
        <h3>上传法律文书</h3>
        <Divider />
        <UploadCom
          frontend="frontendedoc"
          onSuccess={({ storeId, name, files }: any) => {
            console.log('files', files)
            docs.set(files.name, { storeId, name })
          }}
          onRemove={(file: any) => {
            docs.delete(file.name)
            console.log('onRemove', file)
          }}
          title="上传法律文书"
        />
        <h3>处理人拍照</h3>
        <Divider />
        <UploadCom
          frontend="frontendepic"
          onSuccess={({ storeId, name, files }: any) => {
            console.log('files', files)
            dealPics.set(files.name, { storeId, name })
          }}
          onRemove={(file: any) => {
            dealPics.delete(file.name)
            console.log('onRemove', file)
          }}
          title="领取人拍照"
        />
        <FooterAction>
          {isWait ? (
            <div>
              <Button onClick={() => navigate(-1)}>返回</Button>
              <Button
                onClick={() => {
                  onClickBorrowCertficate(true)
                }}
                style={{ marginLeft: 8 }}
              >
                预览处理凭证
              </Button>
              <Button onClick={() => onClickBorrowCertficate()} style={{ marginLeft: 8 }} type="primary">
                制作处理凭证
              </Button>
            </div>
          ) : (
            <Button onClick={() => navigate(-1)}>返回</Button>
          )}
        </FooterAction>
      </main>
      <SuccessModal visible={successVisible} />
      <PropertySelect
        selectedItems={selectedItems}
        setSelectedItems={setSelectedItems}
        castItems={castItems}
        setSelectVisible={setSelectVisible}
        visible={selectVisible}
        handleGetCastItems={handleGetCastItems}
      />
      <ProductionVoucher
        onOk={() => {
          setCertificateVisible(false)
        }}
        onCancel={() => {
          setCertificateVisible(false)
        }}
        visible={certificateVisible}
      />
    </div>
  )
}

export default PropertyInvolved
